﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Net.Sockets;
using System.Threading;
namespace CommunicationProtocol
{
    /// <summary>
    /// 机架通信接口
    /// 子系统，集线器统一实现
    /// 轮询机架信息时，轮询的类统一实现此接口
    /// 金玉堂
    /// 2013-6-20
    /// </summary>
    abstract class ACommunicationProtocolBase : ICommunicationProtocolBase
    {
        public Socket socket;
        public string[,] protocolFormat = null;

        // 取得告警消息
        public abstract Dictionary<object, object> getAlarms();
        //取得状态
        public abstract Dictionary<object, object> getParameters();
        //设定参数
        public abstract bool setParameter(EStanderParaName pName, object pValue);

        //返回对应的协议实例
        public static ICommunicationProtocolBase getCommunicationProtocol(string CommunicationProtocolName, Object[] args)
        {
            return (ICommunicationProtocolBase)System.Activator.CreateInstance(Type.GetType("CommunicationProtocol." + CommunicationProtocolName), args);
        }

        /// <summary>
        /// 初始化socket
        /// </summary>
        /// <param name="socket"></param>
        public ACommunicationProtocolBase(Socket socket)
        {
            this.socket = socket;
        }

        /// <summary>
        /// 负责发送命令并取得返回的数据
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        public byte[] sendAndReceive(byte[] command)
        {
            int length = 0;
            byte[] buffer = new byte[1024];

            try
            {
                socket.Send(command);
                Thread.Sleep(30);
                length = this.socket.Receive(buffer);
            }
            catch(Exception e)
            {
                Console.WriteLine(e.Message);
            }

            byte[] dataReturn = new byte[length];
            Array.Copy(buffer, dataReturn, length);

            return dataReturn;
        }

        /// <summary>
        /// 解析数据，让每个协议类继承实现
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public Dictionary<object, object> dataAnalaize(byte[] data)
        {
            Console.WriteLine(protocolFormat);
            //foreach (object o in protocolFormat)
            //{

            //}
            return null;
        }
    }
}
